<template>
  <div class="codeEdit" :class="className">
    <textarea ref="mycode" class="codesql" v-model="programe_source_local" style="margin-top:30px;width: 100vw;height: 900px"></textarea>
  </div>
</template>

<script>
import "codemirror/theme/ambiance.css";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/hint/show-hint.css";
let CodeMirror = require("codemirror/lib/codemirror");
require("codemirror/addon/edit/matchbrackets");
require("codemirror/addon/selection/active-line");
require("codemirror/mode/sql/sql");
require("codemirror/mode/python/python");
require("codemirror/addon/hint/show-hint");
require("codemirror/addon/hint/sql-hint");
import 'codemirror/lib/codemirror.css'
// 引入主题后还需要在 options 中指定主题才会生效
import 'codemirror/theme/cobalt.css'
import LogMenu from "./LogMenu";
import Jmenu from "../menu/Jmenu";
export default {
  data(){
    return {
      className:"",
      programe_source_local:this.programe_source
    }
  },
  props:{
    programe_source:{
      type:String,
      default:''
    },
    language:{
      type:String,
      default:''
    },
    onChange:{
      type:Function,
      default:function (value){

      }
    }
  },
  components:{
    CodeMirror,
  },
  name: "CodeEdit",
  watch:{
    programe_source:{ //监听的对象
      deep:true, //深度监听设置为 true
      handler:function(newV,oldV){
        try{
          if (this.editor.getValue()!==this.programe_source){
            this.editor.setValue(this.programe_source_local)
          }

        }
        catch (e){

        }

      }
    }
  },
  created(){
    this.getClass();
  },
  methods:{
    setCodePannleWidth(){
      let ele=document.querySelector(".CodeMirror")
      ele.style.height="100%"
      ele.style.width="100%"
    },
    getClass()
    {
      if (!this.className){
        this.className = "class-"+((new Date()).valueOf().toString()*1000)
      }
      return this.className
    }
  },
  mounted(){
    let mime = this.language
    let editor = CodeMirror.fromTextArea(this.$refs.mycode, {
      theme: "cobalt",
      mode: mime,//
      indentWithTabs: true,
      smartIndent: true,
      lineNumbers: true,
      // matchBrackets: true,
      //theme: theme,
      autofocus: false,
      extraKeys: {'Ctrl': 'autocomplete'},//自定义快捷键
      hintOptions: {
        completeSingle: false
      }
    })
    //代码自动提示功能，记住使用cursorActivity事件不要使用change事件，这是一个坑，那样页面直接会卡死
    let self=this;
    editor.on('keypress', function () {
      self.programe_source_local=editor.getValue();
      self.onChange(self.programe_source_local)
      editor.showHint()
    })
    editor.on('change', function () {
      self.programe_source_local=editor.getValue();
      self.onChange(self.programe_source_local)
    })
    this.editor=editor;
    this.setCodePannleWidth();
    window.onresize=()=>{
      this.setCodePannleWidth();
    }
  }
}
</script>

<style scoped>
.codeEdit{
  width: 100%;
  height: 100%;
}
</style>
